# -*- coding: utf-8 -*-
import pymysql
import time
from .user import check_authcode


def reply_list(uid, authcode, page=1, pid=None, rid=None):
    s, data = check_authcode(uid, authcode)
    if not s:
        return False, data
    with mysql(db="BBS") as cur:
        if pid:
            cur.execute(
                """
                SELECT *
                FROM replies
                WHERE pid = %s
                ORDER BY ts DESC
                LIMIT 50
                OFFSET %s;
                """,
                (pid, (page - 1) * 50))
        elif rid:
            cur.execute(
                """
                SELECT *
                FROM replies
                WHERE to_rid = %s
                ORDER BY ts DESC
                LIMIT 50
                OFFSET %s;
                """,
                (rid, (page - 1) * 50))
        else:
            raise ValueError("必须提供rid或pid任意一个")
    return True, cur.fetchall()


def reply(uid, authcode, pid, content):
    s, data = check_authcode(uid, authcode)
    if not s:
        return False, data
    if not content:
        return False, "内容不能为空"
    ts = int(time.time())
    with mysql(db="BBS") as cur:
        row = cur.execute(     # 回复数+1, 修改最后回帖记录
            """
            UPDATE posts SET
            reply_count = reply_count + 1,
            last_reply_uid = %s,
            last_reply_name = %s,
            last_reply_ts = %s
            WHERE pid = %s;
            """,
            (data["uid"], data["screenName"], ts, pid))
        if row == 0:
            return False, "pid不存在"
        cur.execute(     # 添加回复
            """
            INSERT INTO replies
            VALUES (NULL, %s, %s, %s, NULL, NULL, NULL, %s, %s);""",
            (data["uid"], pid, data["screenName"], content, ts))
        return True, cur.lastrowid


def reply_to_reply(uid, authcode, rid, content):
    s, data = check_authcode(uid, authcode)
    if not s:
        return False, data
    if not content:
        return False, "内容不能为空"
    ts = int(time.time())
    with mysql(db="BBS") as cur:
        cur.execute(
            """
            SELECT uid, pid, author_name
            FROM replies
            WHERE rid = %s;
            """,
            (rid, ))
        r = cur.fetchone()
        if not r:
            return False, "rid不存在"
        cur.execute(
            """
            INSERT INTO replies
            VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, %s);
            """,
            (uid, r["pid"], data["screenName"], rid,
             r["author_name"], r["uid"], content, ts))
        return True, cur.lastrowid
